<template>
  <div>
    <!-- 换货 -->
    <!-- <el-descriptions :column="1" border title="商品信息" class="mt-2">
            <el-descriptions-item label="商品编码" label-align="center" width="100px">
                {{ props.productForm.goodsCode }}
            </el-descriptions-item>
            <el-descriptions-item label="商品名称" label-align="center" width="100px">
                {{ props.productForm.goodsTitle }}
            </el-descriptions-item>
            <el-descriptions-item label="商品规格" label-align="center" width="100px">
                {{ props.productForm.goodsSpecName }}
            </el-descriptions-item>
            <el-descriptions-item label="眼别" label-align="center" width="100px">
                <el-tag type="success">
                    {{
                        props.productForm.eyeType == 1
                            ? "左眼"
                            : props.productForm.eyeType == 2
                                ? "右眼"
                                : "综合"
                    }}
                </el-tag>
            </el-descriptions-item>
        </el-descriptions> -->

    <el-form :model="addForm" ref="addFormRef" label-suffix=":" :rules="rules">
      <el-descriptions :column="1" border>
        <el-descriptions-item
          label="商品编码"
          label-align="center"
          width="100px"
        >
          {{ props.productForm.goodsCode }}
        </el-descriptions-item>
        <el-descriptions-item
          label="商品名称"
          label-align="center"
          width="100px"
        >
          {{ props.productForm.goodsTitle }}
        </el-descriptions-item>
        <el-descriptions-item
          label="商品规格"
          label-align="center"
          width="100px"
        >
          {{ props.productForm.goodsSpecName }}
        </el-descriptions-item>
        <el-descriptions-item label="眼别" label-align="center" width="100px">
          <el-tag type="success">
            {{
              props.productForm.eyeType == 1
                ? "左眼"
                : props.productForm.eyeType == 2
                ? "右眼"
                : "综合"
            }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item
          label="源订单号(销售单号)"
          label-align="center"
          width="100px"
        >
          {{ addForm.oldOrderCode }}
        </el-descriptions-item>

        <el-descriptions-item
          label="换货商品总价(元)"
          label-align="center"
          width="100px"
        >
          {{ addForm.totalAmount ? addForm.totalAmount.toFixed(2) : 0 }}
        </el-descriptions-item>

        <el-descriptions-item
          label="换货类型"
          label-align="center"
          width="100px"
        >
          <el-tag type="primary">换货</el-tag>
        </el-descriptions-item>

        <el-descriptions-item label-align="center" width="100px">
          <template #label>
            <div class="flex justify-center items-center">
              <div>换货总差价(元)</div>
              <el-popover placement="right" width="350px">
                <template #default>
                  <div class="mb-1">
                    <el-tag type="danger">-负值 :</el-tag>
                    <span class="ml-1">补差价给到客户</span>
                  </div>
                  <div>
                    <el-tag type="warning">+正值 :</el-tag>
                    <span class="ml-1">客户补差价给到自己</span>
                  </div>
                </template>
                <template #reference>
                  <el-icon style="cursor: pointer; color: #1a7de3">
                    <QuestionFilled />
                  </el-icon>
                </template>
              </el-popover>
            </div>
          </template>
          <el-form-item prop="returnAmount">
            <el-input-number
              v-model="addForm.returnAmount"
              placeholder="请输入换货总差价"
              class="w-full"
              :precision="2"
            />
          </el-form-item>
        </el-descriptions-item>

        <el-descriptions-item
          label="换货商品库存编码"
          label-align="center"
          width="100px"
        >
          <el-form-item prop="oldCodes">
            <el-select
              v-model="addForm.oldCodes"
              multiple
              filterable
              placeholder="请选择换货商品库存编码"
              :multiple-limit="addForm.quantity"
              class="w-full"
            >
              <el-option
                v-for="(item, index) in props.productForm.nowCodes"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-descriptions-item>

        <el-descriptions-item
          label="换货数量"
          label-align="center"
          width="100px"
        >
          <!-- <el-form-item prop="quantity">
                        <el-input-number v-model="addForm.quantity" placeholder="请输入换货数量" class="w-full" :min="1"
                            :max="addForm.max_num" @input="handleJudge" />
                    </el-form-item> -->
          <template #label>
            <div class="flex justify-center items-center">
              <div>换货数量</div>
              <el-popover placement="right" width="350px">
                <template #default>
                  根据选择的
                  <el-tag type="primary">换货商品库存编码</el-tag>
                  进行计算所得
                </template>
                <template #reference>
                  <el-icon style="cursor: pointer; color: #1a7de3">
                    <QuestionFilled />
                  </el-icon>
                </template>
              </el-popover>
            </div>
          </template>
          {{ addForm.oldCodes.length }}
        </el-descriptions-item>

        <el-descriptions-item label="备注" label-align="center" width="100px">
          <el-form-item prop="remark">
            <el-input
              v-model="addForm.remark"
              type="textarea"
              :rows="1"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>

      <!-- <el-form-item label="换货类型" class="mt-2" prop="returnType">
        <el-radio-group v-model="addForm.returnType" size="large">
          <el-radio-button
            v-for="item in refund_type_list"
            :key="item.id"
            :value="item.id"
          >
            <el-card>
              <img :src="item.src" alt="" class="imgUrl" />
              <div>
                {{ item.name }}
              </div>
            </el-card>
          </el-radio-button>
        </el-radio-group>
      </el-form-item> -->
    </el-form>

    <div class="flex justify-between items-center my-2">
      <el-tag>新商品</el-tag>
      <el-button
        type="primary"
        icon="Plus"
        @click="add_production_btn(1)"
        :disabled="newTableData && newTableData.length > 0"
        :title="
          newTableData && newTableData.length > 0 ? '只能选择同一种商品' : ''
        "
        >选择商品</el-button
      >
    </div>
    <el-table :data="newTableData" style="width: 100%">
      <el-table-column prop="goodsCode" label="商品编码" align="center" />
      <el-table-column
        prop="goodsTitle"
        label="商品名称"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="goodsSpecName"
        label="商品规格"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column prop="priceAtOrder" label="零售单价(元)" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.priceAtOrder"
            :precision="2"
            :min="0"
            class="w-full"
          />
        </template>
      </el-table-column>
      <el-table-column prop="priceAtOrder" label="售出数量(件)" align="center">
        <template #default="{ row }">
          <el-input-number v-model="row.count" :min="1" class="w-full" />
        </template>
      </el-table-column>
      <el-table-column prop="priceAtOrder" label="分项价(元)" align="center">
        <template #default="{ row }">
          {{
            new Decimal(row.priceAtOrder).mul(new Decimal(row.count))
              ? new Decimal(row.priceAtOrder)
                  .mul(new Decimal(row.count))
                  .toNumber()
                  .toFixed(2)
              : 0
          }}
        </template>
      </el-table-column>
      <el-table-column prop="priceAtOrder" label="分项直减(元)" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.discount"
            :precision="2"
            :min="0"
            :max="
              new Decimal(row.priceAtOrder)
                .mul(new Decimal(row.count))
                .toNumber()
            "
            :title="`分项直减金额不得超过商品总价${new Decimal(row.priceAtOrder)
              .mul(new Decimal(row.count))
              .toNumber()}元`"
            class="w-full"
          />
        </template>
      </el-table-column>
      <el-table-column prop="priceAtOrder" label="分项优惠(元)" align="center">
        <template #default="{ row }">
          {{ row.subItemDiscount ? row.subItemDiscount.toFixed(2) : 0 }}
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="分项应收(元)" align="center">
        <template #default="{ row }">{{
          row.amount ? row.amount.toFixed(2) : 0
        }}</template>
      </el-table-column>
      <!-- <el-table-column label="眼别" align="center">
        <template #default="{ row }">
          <el-tag
            :type="
              row.eyeType == 2
                ? 'primary'
                : row.eyeType == 3
                ? 'success'
                : 'info'
            "
          >
            {{ row.eyeType == 1 ? "左眼" : row.eyeType == 2 ? "右眼" : "综合" }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="amount" label="操作" align="center" width="180">
        <template #default="{ row }">
          <el-button type="danger" link @click="handleDelete(row.id)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 选择商品页面 -->
    <el-drawer
      v-model="change_production_drawer"
      direction="rtl"
      @close="change_production_drawer = false"
      size="95%"
      title="选择商品"
    >
      <!-- <ChangeProduction
        :eyeType="props.productForm.eyeType"
        @handleForm="handleForm"
      /> -->
    </el-drawer>

    <div class="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ loading ? "提交中..." : "提交" }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { returnType } from "./type.js";
import { cloneDeep } from "lodash";
import Decimal from "decimal.js";
// import ChangeProduction from "../production.vue";
// import { createReturnOrder } from "../../api/api.js";
import { handleApiResponse } from "@/utils/request.js";
import { CreateReturnOrder } from "../../../../../../wailsjs/go/api/OrderApi";

onMounted(() => {
  // console.log(props);

  const { id, orderCode, customerId } = props.detailForm;
  const { amount, count, returnQuantity } = props.productForm;
  addForm.value.oldOrderId = id; // 订单id
  addForm.value.oldOrderCode = orderCode; // 源订单号
  addForm.value.customerId = customerId; // 客户id
  addForm.value.totalAmount = amount ? amount / 100 : 0; // 换货商品总价
  // addForm.value.returnAmount = amount ? amount / 100 : 0; // 退款总金额 -->退款时填写
  addForm.value.quantity = count - returnQuantity; // 换货数量
  addForm.value.max_num = count - returnQuantity; // 限制换货最大数量       - returnQuantity
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  productForm: {
    type: Object,
    default: {},
  },
  detailForm: {
    type: Object,
    default: {},
  },
});

const addFormRef = ref(null);
const addForm = ref({
  oldOrderId: null, // 订单id
  oldOrderCode: "", // 销售单号
  customerId: null,
  oldOrderItemId: null,
  totalAmount: null, // 换货商品总价
  returnAmount: null, // 退款总金额 -->换货退款填写
  quantity: null, // 换货数量
  returnType: 3, // 换货类型
  remark: "",
  oldCodes: [], // 换货商品一物一码
  newOrderItem: {},
});

// 判断数量是否小于编码的长度
const handleJudge = () => {
  if (addForm.value.quantity < addForm.value.oldCodes.length) {
    addForm.value.oldCodes = [];
    ElMessage.warning("请选择换货数量与换货商品编码数量一致");
  }
};

const handleClose = (val = 0) => {
  emit("handleBack", val);
};

const loading = ref(false);
const handleSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      let form = cloneDeep(addForm.value);
      let cloneTableData = cloneDeep(newTableData.value);
      cloneTableData.forEach((item) => {
        item.priceAtOrder = mulTen(item.priceAtOrder);
        item.subItemDiscount = mulTen(item.subItemDiscount);
        item.discount = mulTen(item.discount);
        item.amount = mulTen(item.amount);
        item.ignoreStock = item.ignoreStock ? 1 : 2;
      });

      form.newOrderItem = cloneTableData[0];

      form.oldOrderItemId = props.productForm.id;
      form.returnAmount = initPrice(form.returnAmount);
      form.totalAmount = initPrice(form.totalAmount);
      form.quantity = form.oldCodes.length || 0;
      // console.log(form);

      loading.value = true;
      handleApiResponse(() => CreateReturnOrder({ item: form })).then((res) => {
        if (res.code == 0) {
          ElMessage.success("操作成功");
          handleClose(1);
          loading.value = false;
        } else {
          loading.value = false;
        }
      });
    }
  });
};

// 选择换货的新商品
const newTableData = ref([]);
const change_production_drawer = ref(false);
const add_production_btn = () => {
  change_production_drawer.value = true;
};
const handleForm = (row) => {
  row.id = new Date().getTime();
  newTableData.value.push(row);
  change_production_drawer.value = false;
};

// 删除单个商品
const handleDelete = (id) => {
  newTableData.value = newTableData.value.filter((item) => item.id != id);
};

const initPrice = (num) => {
  let price = null;
  if (!num || typeof num != "number") return 0;
  price = new Decimal(num).mul(new Decimal(100)).toString();
  return +price;
};

const rules = ref({
  oldCodes: [
    {
      required: true,
      message: "请选择换货商品编码",
    },
  ],
  returnType: [
    {
      required: true,
      message: "请选择换货类型",
    },
  ],
  remark: [
    {
      required: false,
      message: "请输入备注",
    },
  ],
  returnAmount: [
    {
      required: true,
      message: "请输入换货差价",
    },
  ],
});

// 计算金额
const computeTotal = () => {
  newTableData.value.forEach((item) => {
    // 防止清空输入框的时候报错，默认为0
    if (!item.priceAtOrder) item.priceAtOrder = 0;
    if (!item.count) item.count = 1;
    if (!item.discount) item.discount = 0;

    // 1.分项优惠金额
    item.subItemDiscount = 0;
    item.subItemDiscount = new Decimal(item.priceAtOrder)
      .mul(new Decimal(item.count))
      .sub(new Decimal(item.priceAtOrder).mul(new Decimal(item.count)))
      .add(item.discount)
      .toNumber();

    // 2.分项应收金额
    item.amount = 0;
    item.amount = new Decimal(item.priceAtOrder)
      .mul(new Decimal(item.count))
      .sub(new Decimal(item.subItemDiscount))
      .toNumber();
  });
};

watchEffect(() => {
  computeTotal();
});

/** 
  @param {Number} num
  @return 数字乘以100后的结果
*/
function mulTen(num) {
  let initNum = new Decimal(num).mul(new Decimal(100)).toString();
  return +initNum;
}
</script>

<style scoped lang="scss">
.el-form-item {
  margin-bottom: 0;
}

.returnType {
  @apply w-full flex justify-between;
}

.el-card {
  width: 100%;
  height: 100%;
  @apply flex flex-col justify-center items-center text-center;

  .imgUrl {
    width: 60px;
    height: 60px;
  }
}

:deep(.el-card__body) {
  padding: 5px !important;
}

.footer {
  @apply fixed bottom-2 right-2 z-[999];
  background-color: white;
}
</style>